﻿using System.Windows.Forms;
using AviationSimulator.DataItems;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using AviationSimulator.Properties;

namespace AviationSimulator.Managers
{
    public class ParametersManager
    {
        private List<string> _parameters;

        public ParametersManager()
        {
            LoadParameters();            
        }

        public IEnumerable<string> Parameters
        {
            get
            {
                return _parameters;
            }
        }

        private void LoadParameters()
        {
            _parameters = new List<string>();

            try
            {
                using (var file = new StreamReader(Settings.Default.ParametersFile))
                {
                    string line;
                    while ((line = file.ReadLine()) != null)
                    {
                        _parameters.Add(line);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(Resources.ParametersLoadError,
                                                     Resources.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void AddParameter(string parameterName)
        {
            if (!_parameters.Contains(parameterName))
            {
                _parameters.Add(parameterName);
                SaveParameters();
            }
            else
            {
                MessageBox.Show("Parameter already exists");
            }
        }

        public void DeleteParameter(string parameterName)
        {
            _parameters.Remove(parameterName);
            SaveParameters();
        }

        private void SaveParameters()
        {
            try
            {
                using (var streamWriter = new StreamWriter(Settings.Default.ParametersFile))
                {
                    streamWriter.Write(string.Empty);

                    foreach (var parameter in _parameters)
                    {
                        streamWriter.WriteLine(parameter);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(Resources.SaveParametersError,
                                                    Resources.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
